"""
Generate 50 inventory records matching YonYou stock query response fields.
Outputs:
- data/inventory_records_50.json (UTF-8)
- data/inventory_records_50.csv (UTF-8 with header)
"""
import os, json, csv, random
from datetime import datetime

from app.services.data_generator import DataGenerator


def map_item(item: dict, billnum: str | None = None) -> dict:
    # Base quantities
    current_qty = item["current_stock"]
    reserved_qty = item.get("reserved_stock", max(0, int(current_qty * 0.1)))
    # Simulate in-notice and pre-retail quantities
    in_notice_qty = max(0, int(current_qty * random.uniform(0, 0.2)))
    pre_retail_qty = max(0, int(current_qty * random.uniform(0, 0.1)))

    # Available qty rule (keep in sync with InventoryService._calculate_available_qty)
    base_available = current_qty - reserved_qty
    if not billnum:
        available_qty = base_available
    else:
        rules = {
            "voucher_order": base_available,
            "voucher_delivery": base_available - int(reserved_qty * 0.5),
            "ec_tradeorder_add": base_available - int(reserved_qty * 0.3),
            "st_transferapply": current_qty - reserved_qty - pre_retail_qty,
            "st_purchaseorder": current_qty + in_notice_qty - pre_retail_qty,
            "po_picking_requisition": current_qty,
            "st_othoutrecord": base_available,
        }
        available_qty = rules.get(billnum, base_available)
    available_qty = max(0, available_qty)

    return {
        # 1. 组织
        "org": item.get("org_id", "1891127153005312"),
        # 2. 仓库
        "warehouse": item["warehouse_id"],
        # 3-5. 物料基础
        "product": item["material_id"],
        "product_name": item["material_name"],
        "product_code": item["material_code"],
        # 6-8. SKU
        "productsku": item.get("productsku_id", item["material_id"]),
        "productsku_name": item.get("productsku_name", item["material_name"]),
        "productsku_code": item.get("productsku_code", item["material_code"]),
        # 9-11. 管理类
        "manageClass": item.get("manage_class_id", "2000100011111111"),
        "manageClass_code": item.get("manage_class_code", "YCL_001"),
        "manageClass_name": item.get("manage_class_name", "原材料库"),
        # 12. 计量单位
        "unit": item.get("unit_id", "1921568854316953"),
        # 13-18. 核心库存数量
        "currentqty": current_qty,
        "availableqty": available_qty,
        "innoticeqty": in_notice_qty,
        "planavailableqty": max(0, available_qty + int(in_notice_qty * 0.5)),
        "preretailqty": pre_retail_qty,
        "stockStatusDoc": item.get("stock_status_doc", 2006555827382257),
        # 19-22. 批次信息
        "batchno": item.get("batch_no"),
        "productionDate": item.get("production_date"),
        "expiryDate": item.get("expiry_date"),
        "batchStatus": item.get("batch_status"),
    }


def main(count: int = 50):
    os.makedirs("data", exist_ok=True)
    base_items = DataGenerator.generate_inventory_items(count=count)
    records = [map_item(x) for x in base_items]

    json_path = os.path.join("data", f"inventory_records_{count}.json")
    csv_path = os.path.join("data", f"inventory_records_{count}.csv")

    # Write JSON
    with open(json_path, "w", encoding="utf-8") as jf:
        json.dump(records, jf, ensure_ascii=False, indent=2)

    # Write CSV
    fieldnames = list(records[0].keys()) if records else []
    with open(csv_path, "w", encoding="utf-8", newline="") as cf:
        writer = csv.DictWriter(cf, fieldnames=fieldnames)
        writer.writeheader()
        for r in records:
            writer.writerow(r)

    print("Generated:")
    print(" ", json_path)
    print(" ", csv_path)


if __name__ == "__main__":
    main(50)
